package com.fingard.dsp.bank.directbank.gdb01;


import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.*;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class GDB01SinglePay extends GDB01Base implements ISinglePay {

    //单笔支付，不需采用流处理方式
    public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
        RetAtsSglDetail tmpRetDetail;
        tmpRetDetail = d_190802(p_req1908);

        if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
            tmpRetDetail.reqSeqID = p_req1908.singleDetail.askNumber;
        }
        retAts.writeRetDetail(tmpRetDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
        return null;
    }

    //190802对外支付
    private RetAtsSglDetail d_190802(ReqSingle p_req1908) throws Exception {
        RetAtsSglDetail retDetail = new RetAtsSglDetail();
        //赋值通用参数
        GDB01Header bankHeader = new GDB01Header();
        bankHeader.entSeqNo = p_req1908.singleDetail.askNumber;
        bankHeader.retCode = "000";//固定值，比填项
        if (p_req1908.singleDetail.sameBnk.equals("1")) {
            bankHeader.tranCode = "0011";//行内（同行）
        } else {
            bankHeader.tranCode = "0021";//行外（跨行）
        }

        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        xmlWriter.autoFormat = false;//报文串需要整个字符串传送，中间需无回车符，否则会签名出错
        writeCommonHeader(xmlWriter, bankHeader);
        //需要进行对账码拼接以及节点解析，采用XElement进行处理
        XElement tmpXElement = new XElement("Body", "");
        if (bankHeader.tranCode.equals("0011")) {
            tmpXElement.addChild(new XElement("traceNo", p_req1908.reqHeader.transSeqID));//网银流水号
        }
        //定义0011和0021的公共节点
        tmpXElement.addChild(new XElement("outAccName", p_req1908.singleDetail.payName));
        tmpXElement.addChild(new XElement("outAcc", p_req1908.singleDetail.payAct));
        tmpXElement.addChild(new XElement("outAccBank", p_req1908.singleDetail.payBankName));
        tmpXElement.addChild(new XElement("inAccName", p_req1908.singleDetail.recName));
        tmpXElement.addChild(new XElement("inAcc", p_req1908.singleDetail.recAct));
        tmpXElement.addChild(new XElement("inAccBank", p_req1908.singleDetail.recBankName));
        tmpXElement.addChild(new XElement("inAccAdd", p_req1908.singleDetail.recAreaName));
        tmpXElement.addChild(new XElement("amount", p_req1908.singleDetail.payAmount));
        tmpXElement.addChild(new XElement("remark", p_req1908.singleDetail.memo));
        if (bankHeader.tranCode.equals("0011")) {
            tmpXElement.addChild(new XElement("date", p_req1908.singleDetail.payDate));//支付日期？
        }
        //定义0011和0021的公共节点comment
        tmpXElement.addChild(new XElement("comment", p_req1908.singleDetail.abstractATS));
        if (bankHeader.tranCode.equals("0011")) {
            tmpXElement.addChild(new XElement("creNo", ""));//凭证号码
            tmpXElement.addChild(new XElement("frBalance", ""));//转出余额
            tmpXElement.addChild(new XElement("toBalance", ""));//转入余额
            tmpXElement.addChild(new XElement("handleFee", ""));//手续费

        } else {
            tmpXElement.addChild(new XElement("paymentBankid", p_req1908.singleDetail.cnapsCode));//联行号
        }
        nodeAnalysis(p_req1908.singleDetail.srcXElement, tmpXElement, getCharset());
        xmlWriter.writeXElement(tmpXElement);
        xmlWriter.writeEndDocument();//写入报文完成
        //System.out.println("dsp接收报文："+xmlWriter.toXmlString());//打印返回报文
        String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());//发送银行
        //测试代码
//	    String[] tmpStrRet = {"",""};
//		tmpStrRet[0]="";
//		tmpStrRet[1]="<?xml version=\1.0\" encoding=\"gbk\" ?><BEDC><Message><commHead><tranCode>0011</tranCode><cifMaster>1000194103</cifMaster><entSeqNo>26082700427648</entSeqNo><tranDate>20160827</tranDate><tranTime>123717</tranTime><retCode>000</retCode><entUserId>100001</entUserId><password>5e93febf8f3df0af0d9d735e03bb25ac50bbee5b1031c23c77e2d1300a31cf01cc02d76cd8c988379892f7b8814e79f5899a18cf98f8d48ac59137b4f481ee31c1075bbd8c5449c8bb9bc6a84ed00e10ba0f641f72105f649dd3c1819f2fe3e1b77deaaa66916d0e38ead23e918d279cdf24b27fba941d59e3bbaf0934437bbefd7f9a42fdeedb263b64928a5605ea2f30f1ecbdb518cb40be9b81cfb0777e673e792c68c0b8626219881d07f0e6364aba03996cd3373ecd4c817bbbdae1518d2e8009e7aee0f7f1b2fb262f7813a417c48dc087bbe7d14e6b302838dbd389c3c04b261562e38377be0f3cd15ec47d172d75b8ce56a36fe9d0d8b42464f37eb8</password></commHead><Body><traceNo>RT2000040546681</traceNo><outAccName>UAT银企客户接入058</outAccName><outAcc>9550880200181500240</outAcc><outAccBank/><inAccName>郝蛮替</inAccName><inAcc>6214620421000001874</inAcc><inAccBank>广发银行股份有限公司</inAccBank><inAccAdd>天津市_天津市</inAccAdd><amount>10.00</amount><remark>报销</remark><date/><comment>36082700620228</comment><creNo>36082700620228</creNo><frBalance>999663.92</frBalance><toBalance/><handleFee>1.00</handleFee></Body></Message></BEDC>";
        if (tmpStrRet[0].length() == 0) {
            StringBuilder tmpSbMsg = new StringBuilder();
            //解析银行返回
            XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
            if (tmpBkReader != null) {
                String tmpRetCode = tmpBkReader.getFirstText("/BEDC/Message/commHead/retCode");
                retDetail.respCode = "0";
                retDetail.respInfo = tmpRetCode;
                retDetail.reqSeqID = tmpBkReader.getFirstText("/BEDC/Message/commHead/entSeqNo");
                retDetail.transState = tmpRetCode;
                retDetail.payInfoCode = tmpRetCode;
            } else {
                retDetail.respCode = "-1";
                retDetail.respInfo = tmpSbMsg.toString();
            }
        } else if (tmpStrRet[0].equals(ConnState.FAIL)) {
            retDetail.respCode = "0";
            retDetail.respInfo = tmpStrRet[1];
            retDetail.reqSeqID = p_req1908.singleDetail.askNumber;
            retDetail.transState = PaymentState.FAIL_Payment;
            retDetail.payInfoCode = tmpStrRet[0];
        } else {
            retDetail.respCode = "-1";
            retDetail.respInfo = tmpStrRet[1];
        }
        return retDetail;
    }

    //1944 状态查询
    public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
        //返回ATS的对象
        RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);

        RetAtsSglDetail tmpRetAtsDetail = new RetAtsSglDetail();
        GDB01Header bankHeader = new GDB01Header();
        bankHeader.entSeqNo = p_req1944.reqHeader.transSeqID;
        bankHeader.tranCode = "0004";
        bankHeader.retCode = "000";
        XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
        xmlWriter.autoFormat = false;
        writeCommonHeader(xmlWriter, bankHeader);//写入通用的头部节点
        xmlWriter.writeStartElement("Body");
        xmlWriter.writeElementString("origEntseqno", p_req1944.askNumber);
        xmlWriter.writeElementString("origEntdate", p_req1944.bgnDate.substring(0, 10).replaceAll("-", ""));
        xmlWriter.writeEndDocument();
        //	 	System.out.println("dsp接收报文："+xmlWriter.toXmlString());//打印返回报文

        try {
            String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
//			    String[] tmpStrRet = {"",""};
//				tmpStrRet[0]="";
//				tmpStrRet[1]="<?xml version=\"1.0\" encoding=\"gbk\" ?><BEDC><Message><commHead><tranCode>0004</tranCode><cifMaster>1000001316</cifMaster><entSeqNo>201312090001104847</entSeqNo><tranDate>20131209</tranDate><tranTime>104834</tranTime><retCode>000</retCode><entUserId>100001</entUserId><password>9</password></commHead><Body><hostStatus>6</hostStatus></Body></Message></BEDC>";

            if (tmpStrRet[0].length() == 0) {
                StringBuilder tmpSbMsg = new StringBuilder();
                XmlTextReader tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
                if (tmpBkReader != null) {
                    String tmpRetCode = tmpBkReader.getFirstText("/BEDC/Message/commHead/retCode");
                    String tmpHostStatus = tmpBkReader.getFirstText("/BEDC/Message/Body/hostStatus");
                    if (tmpRetCode.equals("000") || tmpRetCode.equals("002")) {
                        if (tmpBkReader.getFirstText("/BEDC/Message/commHead/entSeqNo").equals(p_req1944.reqHeader.transSeqID)) {
                            tmpRetAtsDetail.respCode = "0";
                            tmpRetAtsDetail.respInfo = tmpRetCode;
                            tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                        } else {
                            tmpRetAtsDetail.respCode = "-1";
                            tmpRetAtsDetail.respInfo = "请求REQUEST_SN与响应不相符";
                        }
                        tmpRetAtsDetail.transState = tmpRetCode + "+" + tmpHostStatus;
                        tmpRetAtsDetail.payInfoCode = tmpRetCode;
                    } else {
                        tmpRetAtsDetail.respCode = "-1";
                        tmpRetAtsDetail.respInfo=translateRetCode(tmpRetCode);
                    }
                    if (StringHelper.isNullOrEmpty(tmpRetAtsDetail.reqSeqID)) {
                        tmpRetAtsDetail.reqSeqID = p_req1944.askNumber;
                    }
                } else {
                    tmpRetAtsDetail.respCode = "-1";
                    tmpRetAtsDetail.respInfo = tmpSbMsg.toString();
                }
            } else {
                tmpRetAtsDetail.respCode = "-1";
                tmpRetAtsDetail.respInfo = tmpStrRet[1];
            }
        } catch (Exception e) {
            tmpRetAtsDetail.respCode = "-1";
            tmpRetAtsDetail.respInfo = e.getMessage();
            e.printStackTrace();
        }
        retAts.writeRetDetail(tmpRetAtsDetail);
        return retAts;
    }

    @Override
    public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
        return null;
    }
}
